<?php

declare(strict_types=1);

use app\enum\errcode\ErrCodeEnum;
use app\utils\JwtUtil;
use Dsxwk\Framework\Utils\Exception\CodeException;
use Dsxwk\Framework\WebmanHelper\Validate\Think\BaseRequest;

if (!function_exists('auth')) {
    /**
     * 获取当前登录用户对象
     *
     * @return object|null
     * @throws CodeException
     */
    function auth(): ?object
    {
        $token = JwtUtil::handleToken(request()->header('Authorization'));

        return (object)JwtUtil::verifyAccessToken($token);
    }
}

if (!function_exists('batchUpdateSql')) {
    /**
     * 生成批量更新sql
     *
     * @param       $table      string 数据表
     * @param       $data       array 更新数据
     * @param       $primaryKey string 主键字段
     * @param array $conditions
     *
     * @return false|string
     */
    function batchUpdateSql(string $table = '', array $data = [], string $primaryKey = 'id', array $conditions = []): bool|string
    {
        if (!is_array($data) || !$primaryKey || !is_array($conditions)) {
            return false;
        }

        // 生成批量更新条件
        $sql  = '';
        $keys = array_keys(current($data));
        foreach ($keys as $column) {
            if ($column == $primaryKey) {
                continue;
            }
            $sql .= sprintf('`%s` = CASE `%s` ' . PHP_EOL, $column, $primaryKey);
            foreach ($data as $line) {
                $sql .= sprintf('WHEN \'%s\' THEN \'%s\' ' . PHP_EOL, $line[$primaryKey], $line[$column]);
            }
            $sql .= "END,";
        }

        $caseWhen = rtrim($sql, ',');

        // 解析where条件
        $where = [];
        if (!empty($conditions)) {
            foreach ($conditions as $key => $value) {
                $where[] = sprintf('`%s` = \'%s\'', $key, $value);
            }
        }

        $where = !empty($where) ? ' AND ' . implode(' AND ', $where) : '';

        // 获取所有键名为$field列的值，值两边加上单引号，保存在$fields数组中
        $fields = array_column($data, $primaryKey);
        $fields = implode(
            ',',
            array_map(
                function ($value) {
                    return '\'' . $value . '\'';
                },
                $fields
            )
        );

        return sprintf('UPDATE `%s` SET %s WHERE `%s` IN (%s) %s', $table, $caseWhen, $primaryKey, $fields, $where);
    }
}

if (!function_exists('validated')) {
    /**
     * 公共验证
     *
     * @param $validateRequest
     *
     * @return array
     * @throws CodeException
     */
    function validated($validateRequest): array
    {
        /**
         * @var BaseRequest $validate
         */
        $validate = new $validateRequest;
        $result   = $validate->checked(request()->all());
        if (!$result) {
            throwError(ErrCodeEnum::PARAM_ERROR, $validate->getError());
        }

        return $result;
    }
}